package com.fulihui.usercore.common.util;

import com.google.common.base.Throwables;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Encoder;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;

/**
 * 密码工具
 * Created by Willard.Hu on 2016/5/22.
 */
public class PasswordUtil {

    /**
     * 加密用户密码 MD5(SHA256(longId + passwd + salt))
     * @param loginId 登陆账号
     * @param passwd 密码
     * @param salt 盐
     * @return 加密后的密文
     */
    public static String encryptPassword(String loginId, String passwd, String salt) {
        String encrypt = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
            byte[] bytes = md5.digest(sha256.digest((loginId + passwd + salt).getBytes()));
            encrypt = Hex.encodeHexString(bytes);
        } catch (NoSuchAlgorithmException e) {
            Throwables.propagate(e);
        }
        return encrypt;
    }
    /**
     * 生成随机盐
     * 注册时调用、修改密码时调用更新盐
     * @return 盐
     */
    public static String generateSalt(){
        Random RANDOM = new SecureRandom();
        byte[] salt = new byte[16];
        RANDOM.nextBytes(salt);
        return new BASE64Encoder().encode(salt);
    }
    /**
     * 验证密码是否正确
     * @param loginId 登陆账号
     * @param passwd 密码
     * @param salt 盐
     * @param saved 已保存的密码
     * @return 匹配结果
     */
    public static boolean passwordsMatch(String loginId, String passwd, String salt, String saved) {
        return StringUtils.equals(encryptPassword(loginId, passwd, salt), saved);
    }

}
